package com.ctg.behavior.calc.impala.transfer.userpath;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.report.userpath.CtUserPathNextReport;
import com.ctg.behavior.calc.impala.transfer.CtFilterTransfer;
import com.ctg.behavior.common.calc.CtCalc;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUserPathNextTransfer extends CtFilterTransfer {

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtUserPathNextReport)) {
			log.warn("calcObject is not CtUserPathNextReport, class={}", calcObject.getClass());
			log.warn("calcObject: {}", JSON.toJSON(calcObject));
			log.warn("calcObject-sqlParam: {}", JSON.toJSON(sqlParam));
			return "";
		}
		CtUserPathNextReport report = (CtUserPathNextReport) calcObject;
		log.info("report={}", JSON.toJSONString(report));

		String filterSQL = report.getFilterSQL();
		String thePrefix = "et" + report.getTheColumnIndex();
		String theJoinPrefix = "etj" + report.getTheColumnIndex();

		StringBuilder impalaSQL = new StringBuilder();

		impalaSQL.append(" SELECT DISTINCT ").append(thePrefix).append(".event AS event ");
		impalaSQL.append(" FROM a_event_parquet_").append(report.getAppId()).append(" ").append(thePrefix).append(" ");

		// 条件限制 - user_id 的范围
		impalaSQL.append(" JOIN ( ").append(filterSQL).append(" ) ").append(theJoinPrefix).append(" ");
		impalaSQL.append(" ON ").append(thePrefix).append(".user_id = ").append(theJoinPrefix).append("userId ");
		//
		impalaSQL.append(" WHERE 1=1 ");
		// 由于留存用户信息，需要在时间先后限制： 后续事件发生时间必须大于上级事件的时间
		impalaSQL.append(" AND ").append(thePrefix).append(".event_time > ").append(theJoinPrefix).append("eventTime ");
//
//		// 分组
//		impalaSQL.append(" GROUP BY ").append(thePrefix).append(".event ");
//		// 排序
//		impalaSQL.append(" ORDER BY total DESC ");

		return impalaSQL.toString();
	}

}
